package com.szw.vhrlearn.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.szw.vhrlearn.model.Hr;
import com.szw.vhrlearn.model.RespBean;
import com.szw.vhrlearn.service.HrService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description
 * @Author 申紫微
 * @Data 2020-03-23 23:05:39
 * @Version 1.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    HrService hrService;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hrService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                 anyRequest().authenticated()//所有请求认证之后才可以访问
                .and()
                .formLogin()//表单登录
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/doLogin")//登录处理的url
//                .loginPage("/login")//登录页，本来是存在登录页面的，这里自定义了一个并不存在的页面，所以访问失败的时候，会提示404
                .successHandler(new AuthenticationSuccessHandler() {//登录成功的回调
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        //登录成功的信息在authenticaiton里
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        Hr hr = (Hr) authentication.getPrincipal();
                        hr.setPassword(null);
                        RespBean respbean = RespBean.ok("登录成功", hr);
                        String s = new ObjectMapper().writeValueAsString(respbean);
                        out.write(s);
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {//登录失败的回调
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException execption) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        RespBean resultBean = RespBean.error("登录失败");
                        if(execption instanceof LockedException){
                            resultBean.setMessage("账户已被锁定，请联系管理员");
                        }else if (execption instanceof CredentialsExpiredException){
                            resultBean.setMessage("密码过期，请联系管理员");
                        }else if (execption instanceof AccountExpiredException){
                            resultBean.setMessage("账户过期，请联系管理员");
                        }else if (execption instanceof DisabledException){
                            resultBean.setMessage("账户被禁用，请联系管理员");
                        }else if(execption instanceof BadCredentialsException){
                            resultBean.setMessage("用户名或密码错误");
                        }
                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()//所有接口都可以直接返回？？？不太明白
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功")));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable();
    }
}
